<template>
  <div class="binding">
    <Header>
      <div slot="title" class="header-title">绑定账号</div>
      <div slot="left" class="header-left">
        <img src="@/assets/index/back.png" alt />
      </div>
      <div slot="right" class="header-right">
        <span
          style="color: #0a67da"
          @click="
            () => {
              this.$router.push({ path: '/login/organizaRegistr' });
            }
          "
          >注册</span
        >
      </div>
    </Header>
    <div class="fenge"></div>
    <div class="codeBinding" v-if="phoneBinding">
      <van-form
        :show-error="false"
        validate-first
        validate-trigger="onSubmit"
        @submit="onSubmit"
        ref="phoneBindingform"
      >
        <van-field
          v-model="loginForm.phone"
          @blur="blur('phone', loginForm.phone)"
          @input="change('phone', loginForm.phone)"
          name="phone"
          label="手机号"
          clearable
          placeholder="请输入手机号码"
          :rules="[
            {
              required: true,
              validator: validatePhone,
              message: (value) => {
                if (!value) {
                  return '请输入手机号';
                }
                if (!this.validatePhone(value)) {
                  return '请输入正确的手机号';
                }
              },
            },
          ]"
        ></van-field>
        <van-field
          v-model="loginForm.code"
          @blur="blur('validateCode', loginForm.code)"
          @input="change('validateCode', loginForm.code)"
          type="text"
          name="validateCode"
          label="验证码"
          clearable
          placeholder="请输入验证码"
          :rules="[
            {
              required: true,
              validator: validateCode,
              message: (value) => {
                if (!value) {
                  return '请输入验证码';
                }
                if (!this.validateCode(value)) {
                  return '请输入正确的验证码';
                }
              },
            },
          ]"
        >
          <template class="password-field" slot="right-icon" name="right-icon">
            <span
              class="password-span"
              @click="getCode('phoneBindingform', 'phone')"
              v-if="!countDown"
              >获取验证码</span
            >
            <span class="password-span" v-else
              >重新获取( {{ restTime }} s)</span
            >
          </template>
        </van-field>
      </van-form>
    </div>
    <div class="codeBinding" v-else-if="!phoneBinding">
      <van-form
        :show-error="false"
        validate-first
        validate-trigger="onSubmit"
        ref="phoneBindingform2"
        @submit="onSubmit"
      >
        <van-field
          v-model="loginForm.phone"
          @blur="blur('phone', loginForm.phone)"
          @input="change('phone', loginForm.phone)"
          name="phone"
          label="手机号"
          clearable
          placeholder="请输入手机号码"
          :rules="[
            {
              required: true,
              validator: validatePhone,
              message: (value) => {
                if (!value) {
                  return '请输入手机号';
                }
                if (!this.validatePhone(value)) {
                  return '请输入正确的手机号';
                }
              },
            },
          ]"
        ></van-field>
        <van-field
          v-model="password"
          @blur="blur('password', password)"
          @input="change('password', password)"
          type="password"
          name="password"
          label="密码"
          clearable
          placeholder="请输入密码"
          :rules="[
            {
              required: true,
              validator: validatePass,
              message: (value) => {
                if (!value) {
                  return '请输入密码';
                }
                if (value.length < 6) {
                  return '长度6-20个字符之间';
                }
                if (this._str(value, value[0]) == value.length) {
                  return '不能使用同一字符';
                }
                if (!this.validatePass(value)) {
                  return '非法字符，请使用字母、数字的组合，6-20个字符';
                }
              },
            },
          ]"
        ></van-field>
      </van-form>
    </div>
    <div style="margin: 25px">
      <van-button
        class="bindingButton"
        round
        block
        type="default"
        native-type="submit"
        @click="
          () => {
            this.$refs.phoneBindingform.submit();
          }
        "
        >绑定</van-button
      >
      <p class="kuaijie" @click="gologin">
        {{ phoneBinding ? "密码账号登录" : "手机号码快捷登录" }}
      </p>
    </div>
    <Verify
      @success="sliderPassed"
      :captchaType="captchaType"
      :phone="loginForm.phone"
      :imgSize="{ width: '400px', height: '200px' }"
      ref="captchaVer"
    ></Verify>
  </div>
</template>

<script>
import Header from "@/components/header.vue";
import { Form, Field, Button, Divider } from "vant";
import { getPhoneCodeAPI, bindingUserAPI } from "./api/login";
import Verify from "./component/verifition/Verify";
import {
  CODE_TYPE,
  BUSINESS_TYPE,
  RESET_TIME,
  QQLogin,
  WeChatLogin,
  wbLogin,
} from "./utils/constant";
import {
  warningMessage,
  successMessage,
  errorMessage,
  linkName,
  linkOpen,
} from "./utils/function";
import userInfo from "@/views/login";
export default {
  components: {
    Header,
    Verify,
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [Divider.name]: Divider,
  },
  data() {
    return {
      password: "",
      phoneBinding: true,
      countDown: false,
      restTime: RESET_TIME,
      nickName: userInfo.get("nickName"),
      timer: null,
      captchaType: "", // 滑块验证码方式
      loginLoading: false,
      uuid: "",
      loginForm: {
        phone: "",
        code: "",
      },
    };
  },
  methods: {
    blur(type, v) {
      let me = this;
      if (v) {
        let form = "";
        this.phoneBinding
          ? (form = "phoneBindingform")
          : (form = "phoneBindingform2");
        switch (type) {
          case "password":
            this.$refs[form].validate("password");
            break;
          case "phone":
            this.$refs[form].validate("phone");
            break;
          case "validateCode":
            this.$refs[form].validate("validateCode");
            break;
          default:
            break;
        }
      }
    },
    change(type, v) {
      if (v) {
        let form = "";
        let me = this;
        this.phoneBinding
          ? (form = "phoneBindingform")
          : (form = "phoneBindingform2");
        switch (type) {
          case "password":
            this.$refs[form].validate("password");
            break;
          case "phone":
            this.$refs[form].validate("phone");
            break;
          case "validateCode":
            this.$refs[form].validate("validateCode");
            break;
          default:
            break;
        }
      }
    },
    _str(value, n) {
      var tmp = 0;
      for (var i = 0; i < value.length; i++) {
        if (value.charAt(i) == n) {
          //charAt()方法可返回指定位置的字符
          tmp++;
          console.log(tmp);
        }
      }
      return tmp;
    },
    onSubmit() {
      if (!this.uuid) {
        warningMessage("请先获取验证码");
        return;
      }
      if (this.loginLoading) return;
      this.loginLoading = true;
      let { phone, code } = this.loginForm;
      let form = {
        captchaForm: {
          phone,
          businessType: BUSINESS_TYPE["login"],
          type: CODE_TYPE["phone"],
          uuid: this.uuid,
          value: code,
        },
      };
      bindingUserAPI(form).then(
        (res) => {
          if (res.data.code === 0) {
            let data = res.data.data;
            // canResetPassword: // 用户是否可以重置密码
            // isExsit 0 不存在   1存在
            // userInfo.sign(data);
            userInfo.set("phone", phone);
            successMessage("绑定成功", () => {
              this.$router.push({ path: "/" });
            });
          } else {
            this.loginLoading = false;
            warningMessage(res.data.msg);
          }
        },
        (error) => {
          this.loginLoading = false;
        }
      );
    },
    gologin() {
      this.$router.push({
        path: "/login/sign",
        query: { phoneBinding: this.phoneBinding },
      });
    },
    getCode(refName, name) {
      if (!this.loginForm.phone) {
        warningMessage("请输入手机号");
        return;
      }
      this.$refs[refName].validate(name).then(
        (_) => {
          console.log("打开滑动验证码");
          this.$refs.captchaVer.show();
        },
        (errorMsg) => {
          // warningMessage("手机号输入错误！");
        }
      );
    },
    sliderPassed(val) {
      let { value } = val;
      let self = this;
      getPhoneCodeAPI(val).then((res) => {
        if (res.data.code == 0) {
          this.countDown = true;
          this.uuid = res.data.data.uuid;
          let timer = setInterval(() => {
            if (self.restTime == 0) {
              this.countDown = false;
              clearInterval(timer);
              self.restTime = RESET_TIME;
              return;
            } else {
              self.restTime--;
            }
          }, 1000);
        } else {
          warningMessage(res.data.msg);
        }
      });
    },
    validatePhone(value) {
      let reg = /^(13\d|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18\d|19[89])\d{8}$/;
      return reg.test(value);
    },
    validateCode(value) {
      let reg = /^(\d|\w){4}$/;
      return reg.test(value);
    },
    validatePass(value) {
      let reg = /^(?=.*\d)[A-Za-z\d]{6,20}$/;
      let flag = reg.test(value);
      if(flag){
        flag = !(this._str(value, value[0]) == value.length)
      }
      return flag
    },
  },
  created() {
    this.captchaType = CODE_TYPE["blockPuzzle"];
  },
};
</script>

<style lang="scss">
@import "./css/index.scss";
.binding {
  width: 100%;
  height: 100%;
  .fenge {
    width: 100%;
    height: 15px;
    background-color: #f3f3f3;
  }
}
.bindingButton {
  background-image: url("./img/denglu-but.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100% 100%;
  color: #ffffff;
}
</style>